<template>
  <div class="order-management">
    <!-- 头部快捷操作区 -->
    <div class="quick-actions flex gap-4 p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300">
      <el-button type="primary" size="large" icon="Plus" @click="navigateToNewService">
        预约新服务
      </el-button>
      <el-button size="large" icon="Service" @click="contactCustomerService">
        联系客服
      </el-button>
    </div>

    <!-- 搜索和筛选区 -->
    <div class="search-filter-section p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300">
      <el-input
        v-model="searchQuery"
        placeholder="搜索订单号、宠物名或服务类型"
        prefix-icon="Search"
        @keyup.enter="handleSearch"
        class="w-full max-w-md"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 订单状态分类标签 -->
    <div class="order-tabs p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="custom-tabs">
        <el-tab-pane
          v-for="type in filterTypes"
          :key="type.key"
          :label="type.label"
          :name="type.key"
        >
          <template #label>
            <span>{{ type.label }}</span>
            <el-badge
              v-if="orderCounts[type.key] > 0"
              :value="orderCounts[type.key]"
              class="ml-2"
            />
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 高级筛选器 -->
    <div class="filter-section p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300">
      <el-form :inline="true" class="flex flex-wrap gap-4">
        <el-form-item label="服务类型">
          <el-select v-model="filterForm.serviceType" placeholder="全部">
            <el-option label="美容" value="grooming" />
            <el-option label="医疗" value="medical" />
            <el-option label="寄养" value="boarding" />
            <el-option label="训练" value="training" />
          </el-select>
        </el-form-item>
        <el-form-item label="宠物">
          <el-select v-model="filterForm.petId" placeholder="全部宠物">
            <el-option v-for="pet in pets" :key="pet.id" :label="pet.name" :value="pet.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="排序方式">
          <el-select v-model="filterForm.sortBy" placeholder="默认排序">
            <el-option label="最新创建" value="createTimeDesc" />
            <el-option label="最早创建" value="createTimeAsc" />
            <el-option label="金额从高到低" value="amountDesc" />
            <el-option label="金额从低到高" value="amountAsc" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <div class="order-list p-6 bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300">
      <template v-if="orders.length">
        <el-card
          v-for="order in orders"
          :key="order.id"
          class="order-card mb-4 border border-gray-100 rounded-xl hover:shadow-md transition-all duration-300"
        >
          <div class="order-header flex justify-between items-center pb-4 border-b border-gray-100">
            <div class="order-id font-medium text-gray-700">订单号: {{ order.id }}</div>
            <div class="order-status">
              <el-tag :type="getStatusType(order.status)" effect="light">{{ getStatusText(order.status) }}</el-tag>
            </div>
          </div>
          
          <div class="order-content flex flex-col md:flex-row justify-between items-start md:items-center py-4">
            <div class="pet-info flex items-center mb-4 md:mb-0">
              <el-avatar :src="order.pet.avatar" :size="64" class="mr-4" />
              <div class="pet-details">
                <h4 class="font-medium text-lg text-gray-800">{{ order.pet.name }}</h4>
                <p class="text-gray-500">{{ order.pet.breed }}</p>
              </div>
            </div>
            
            <div class="service-info text-right">
              <div class="service-name font-medium text-gray-800">{{ order.service.name }}</div>
              <div class="service-time text-gray-500 flex items-center justify-end mt-1">
                <el-icon class="mr-1"><Calendar /></el-icon>
                {{ order.service.appointmentTime }}
              </div>
              <div class="service-amount mt-2">
                <span class="amount font-semibold text-orange-500 text-xl">¥{{ order.amount }}</span>
              </div>
            </div>
          </div>
          
          <div class="order-actions flex justify-end pt-4 border-t border-gray-100">
            <el-button size="small" type="text" @click="navigateToDetail(order.id)">查看详情</el-button>
            <el-button 
              v-if="order.status === 'toBeReviewed'" 
              type="primary" 
              size="small" 
              @click="openReviewModal(order)"
            >
              评价服务
            </el-button>
            <el-button 
              v-if="order.status === 'unpaid'" 
              type="primary" 
              size="small" 
              @click="handlePayment(order)"
            >
              立即支付
            </el-button>
            <el-button 
              v-if="order.canCancel" 
              type="danger" 
              size="small" 
              @click="handleCancel(order)"
            >
              取消订单
            </el-button>
          </div>
        </el-card>
      </template>
      <el-empty v-else description="暂无订单" />
    </div>
    
    <!-- 评价模态框 -->
    <el-dialog
      v-model="reviewModalVisible"
      title="服务评价"
      width="40%"
      :before-close="handleCloseReviewModal"
    >
      <template #content>
        <el-form :model="reviewForm" label-width="100px" class="p-4">
          <el-form-item label="总体评分">
            <el-rate v-model="reviewForm.rating" />
          </el-form-item>
          <el-form-item label="服务质量">
            <el-rate v-model="reviewForm.serviceQuality" />
          </el-form-item>
          <el-form-item label="环境设施">
            <el-rate v-model="reviewForm.environment" />
          </el-form-item>
          <el-form-item label="服务态度">
            <el-rate v-model="reviewForm.attitude" />
          </el-form-item>
          <el-form-item label="评价内容">
            <el-input
              v-model="reviewForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入您的评价内容..."
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewModalVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const activeTab = ref('all');
const orders = ref([]);
const orderCounts = ref({
  all: 0,
  unpaid: 0,
  pending: 0,
  inProgress: 0,
  completed: 0,
  cancelled: 0,
  toBeReviewed: 0
});

const filterForm = ref({
  serviceType: '',
  petId: '',
  dateRange: '',
  sortBy: 'createTimeDesc'
});

const searchQuery = ref('');
const reviewModalVisible = ref(false);
const reviewForm = ref({
  orderId: '',
  rating: 5,
  serviceQuality: 5,
  environment: 5,
  attitude: 5,
  content: ''
});

const pets = ref([
  { id: 'pet001', name: '球球' },
  { id: 'pet002', name: '奥利奥' },
  { id: 'pet003', name: '小白' },
  { id: 'pet004', name: '可可' },
  { id: 'pet005', name: 'Lucy' },
  { id: 'pet006', name: 'Max' }
]);

// 订单状态类型映射
const statusMap = {
  unpaid: { text: '待支付', type: 'warning' },
  pending: { text: '待服务', type: 'info' },
  inProgress: { text: '进行中', type: 'primary' },
  completed: { text: '已完成', type: 'success' },
  cancelled: { text: '已取消', type: 'danger' },
  toBeReviewed: { text: '待评价', type: 'warning' }
};

// 订单状态筛选类型
const filterTypes = [
  { key: 'all', label: '全部' },
  { key: 'unpaid', label: '待支付' },
  { key: 'pending', label: '待服务' },
  { key: 'inProgress', label: '进行中' },
  { key: 'completed', label: '已完成' },
  { key: 'cancelled', label: '已取消' },
  { key: 'toBeReviewed', label: '待评价' }
];

// 模拟数据获取 - 保持原有订单数据不变，新增待评价订单
const fetchOrders = async (status = 'all') => {
  // 原有订单数据保持不变
  const originalOrders = [
    {
      id: 'ORD2024001',
      createTime: '2024-03-15 10:30',
      pet: {
        id: 'pet001',
        name: '球球',
        breed: '金毛寻回犬',
        avatar: 'https://picsum.photos/id/237/64/64'
      },
      service: {
        type: 'grooming',
        name: '精致美容套餐',
        appointmentTime: '2024-03-20 14:30'
      },
      amount: 299,
      status: 'pending',
      canCancel: true,
      canModify: true,
      hasReview: false
    },
    {
      id: 'ORD2024002',
      createTime: '2024-03-14 15:20',
      pet: {
        id: 'pet002',
        name: '奥利奥',
        breed: '边境牧羊犬',
        avatar: 'https://picsum.photos/id/169/64/64'
      },
      service: {
        type: 'medical',
        name: '年度体检套餐',
        appointmentTime: '2024-03-18 10:00'
      },
      amount: 599,
      status: 'unpaid',
      canCancel: true,
      canModify: true,
      hasReview: false
    },
    {
      id: 'ORD2024003',
      createTime: '2024-03-13 09:00',
      pet: {
        id: 'pet003',
        name: '小白',
        breed: '柴犬',
        avatar: 'https://picsum.photos/id/1025/64/64'
      },
      service: {
        type: 'training',
        name: '基础训练课程',
        appointmentTime: '2024-03-16 15:00'
      },
      amount: 799,
      status: 'inProgress',
      canCancel: false,
      canModify: false,
      hasReview: false
    },
    {
      id: 'ORD2024004',
      createTime: '2024-03-12 14:00',
      pet: {
        id: 'pet004',
        name: '可可',
        breed: '泰迪犬',
        avatar: 'https://picsum.photos/id/1074/64/64'
      },
      service: {
        type: 'boarding',
        name: '豪华寄养7天',
        appointmentTime: '2024-03-15 09:00'
      },
      amount: 1299,
      status: 'completed',
      canCancel: false,
      canModify: false,
      hasReview: true
    },
    {
      id: 'ORD2024005',
      createTime: '2024-03-10 11:30',
      pet: {
        id: 'pet001',
        name: '球球',
        breed: '金毛寻回犬',
        avatar: 'https://picsum.photos/id/237/64/64'
      },
      service: {
        type: 'grooming',
        name: '洗浴服务',
        appointmentTime: '2024-03-11 16:00'
      },
      amount: 159,
      status: 'completed',
      canCancel: false,
      canModify: false,
      hasReview: true
    }
  ];

  // 新增待评价订单数据 - 不修改原有订单
  const newToBeReviewedOrders = [
    {
      id: 'ORD2024006',
      createTime: '2024-03-18 14:20',
      pet: {
        id: 'pet005',
        name: 'Lucy',
        breed: '拉布拉多',
        avatar: 'https://picsum.photos/id/1024/64/64'
      },
      service: {
        type: 'medical',
        name: '疫苗接种',
        appointmentTime: '2024-03-20 10:00'
      },
      amount: 259,
      status: 'completed',
      canCancel: false,
      canModify: false,
      hasReview: false // 新增待评价订单，未评价
    },
    {
      id: 'ORD2024007',
      createTime: '2024-03-17 09:45',
      pet: {
        id: 'pet006',
        name: 'Max',
        breed: '萨摩耶',
        avatar: 'https://picsum.photos/id/1062/64/64'
      },
      service: {
        type: 'grooming',
        name: '造型修剪',
        appointmentTime: '2024-03-19 15:30'
      },
      amount: 329,
      status: 'completed',
      canCancel: false,
      canModify: false,
      hasReview: false // 新增待评价订单，未评价
    }
  ];

  // 合并所有订单
  let allOrders = [...originalOrders, ...newToBeReviewedOrders];

  // 处理"待评价"状态（已完成但未评价）
  const processedOrders = allOrders.map(order => {
    if (order.status === 'completed' && !order.hasReview) {
      return { ...order, status: 'toBeReviewed' };
    }
    return order;
  });

  // 根据状态筛选订单
  let filteredOrders = processedOrders;
  if (status !== 'all') {
    filteredOrders = processedOrders.filter(order => order.status === status);
  }

  // 应用搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filteredOrders = filteredOrders.filter(order => 
      order.id.toLowerCase().includes(query) ||
      order.pet.name.toLowerCase().includes(query) ||
      order.service.name.toLowerCase().includes(query)
    );
  }

  // 应用排序
  filteredOrders = sortOrders(filteredOrders);

  orders.value = filteredOrders;

  // 更新订单数量统计
  orderCounts.value = {
    all: processedOrders.length,
    unpaid: processedOrders.filter(o => o.status === 'unpaid').length,
    pending: processedOrders.filter(o => o.status === 'pending').length,
    inProgress: processedOrders.filter(o => o.status === 'inProgress').length,
    completed: processedOrders.filter(o => o.status === 'completed').length,
    cancelled: processedOrders.filter(o => o.status === 'cancelled').length,
    toBeReviewed: processedOrders.filter(o => o.status === 'toBeReviewed').length
  };
};

// 订单排序函数
const sortOrders = (orders) => {
  const sortBy = filterForm.value.sortBy;
  
  switch (sortBy) {
    case 'createTimeDesc':
      return [...orders].sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
    case 'createTimeAsc':
      return [...orders].sort((a, b) => new Date(a.createTime) - new Date(b.createTime));
    case 'amountDesc':
      return [...orders].sort((a, b) => b.amount - a.amount);
    case 'amountAsc':
      return [...orders].sort((a, b) => a.amount - b.amount);
    default:
      return orders;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status]?.text || status;
};

// 获取状态标签类型
const getStatusType = (status) => {
  return statusMap[status]?.type || 'info';
};

const handleTabChange = (tab) => {
  activeTab.value = tab;
  fetchOrders(tab);
};

const navigateToNewService = () => {
  router.push('/reservation');
};

const contactCustomerService = () => {
  ElMessage.info('正在连接客服，请稍候...');
};

const navigateToDetail = (orderId) => {
  router.push(`/orders/${orderId}`);
};

const handlePayment = async (order) => {
  try {
    await ElMessageBox.confirm('确认支付订单？', '支付确认');
    // 模拟支付成功
    ElMessage.success('支付成功');
    order.status = 'pending';
    fetchOrders(activeTab.value);
  } catch {
    // 用户取消支付
  }
};

const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm(
      '取消订单后，需要重新预约才能享受服务，是否确认取消？',
      '取消订单',
      {
        type: 'warning'
      }
    );
    // 模拟取消订单
    order.status = 'cancelled';
    order.canCancel = false;
    order.canModify = false;
    fetchOrders(activeTab.value);
    ElMessage.success('订单已取消');
  } catch {
    // 用户取消操作
  }
};

const openReviewModal = (order) => {
  reviewForm.value = {
    orderId: order.id,
    rating: 5,
    serviceQuality: 5,
    environment: 5,
    attitude: 5,
    content: ''
  };
  reviewModalVisible.value = true;
};

const handleCloseReviewModal = (done) => {
  ElMessageBox.confirm('确认要关闭评价窗口吗？您的评价内容将不会保存。', '提示', {
    type: 'warning'
  }).then(() => {
    done();
    reviewModalVisible.value = false;
  }).catch(() => {});
};

const submitReview = async () => {
  try {
    // 模拟提交评价
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 更新订单状态
    const orderIndex = orders.value.findIndex(o => o.id === reviewForm.value.orderId);
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = 'completed';
      orders.value[orderIndex].hasReview = true;
    }
    
    reviewModalVisible.value = false;
    ElMessage.success('评价提交成功，感谢您的反馈！');
    
    // 更新订单列表
    fetchOrders(activeTab.value);
  } catch (error) {
    ElMessage.error('提交评价失败，请稍后重试');
  }
};

const handleSearch = () => {
  fetchOrders(activeTab.value);
};

const resetSearch = () => {
  searchQuery.value = '';
  filterForm.value = {
    serviceType: '',
    petId: '',
    dateRange: '',
    sortBy: 'createTimeDesc'
  };
  fetchOrders(activeTab.value);
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
/* 样式保持不变 */
.order-management {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.quick-actions {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.quick-actions:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.search-filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.search-filter-section:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.search-filter-section .el-input {
  flex: 1;
}

.order-tabs {
  background: white;
  padding: 24px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.order-tabs:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.filter-section {
  background: white;
  padding: 24px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.filter-section:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.order-list {
  display: grid;
  gap: 20px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.order-list:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.order-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.order-id {
  font-weight: 500;
  color: #303133;
}

.order-status .el-tag {
  font-size: 14px;
  padding: 4px 10px;
}

.order-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.pet-info {
  display: flex;
  gap: 16px;
  align-items: center;
}

.pet-details h4 {
  margin: 0 0 4px;
  font-size: 16px;
  font-weight: 500;
}

.pet-details p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.service-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  text-align: right;
}

.service-name {
  font-weight: 500;
  color: #303133;
}

.service-time {
  color: #909399;
  font-size: 14px;
  margin: 4px 0;
}

.service-amount .amount {
  font-size: 18px;
  font-weight: 600;
  color: #e76f51;
}

.order-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 24px;
  height: 48px;
  line-height: 48px;
  transition: all 0.3s ease;
}

:deep(.el-tabs__item.is-active) {
  color: #e76f51;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #e76f51;
  height: 3px;
  border-radius: 3px;
}

:deep(.el-button) {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background-color: #e76f51;
  border-color: #e76f51;
}

:deep(.el-button--primary:hover) {
  background-color: #d65c41;
  border-color: #d65c41;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(231, 111, 81, 0.2);
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

:deep(.el-input) {
  border-radius: 8px;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  border-radius: 8px;
}

:deep(.el-select) {
  width: 180px;
}

:deep(.el-rate) {
  margin-right: 10px;
}

.order-count-badge {
  margin-left: 8px;
}

:deep(.el-empty) {
  padding: 40px 0;
}
</style>